package task

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/ws"

	"ssalarm/common/constant"
	"ssalarm/common/cron"
)

func Start() {
	// 刷新ws客户端权限
	cron.AddCronTask("10 0/3 * * * ?", refreshWsClientAuth, false)
}

func refreshWsClientAuth() {
	if ws.GetClientLen() == 0 {
		return
	}
	keys := env.Cache.ScanKey("login_user:*")
	if len(keys) == 0 {
		return
	}
	uidMapInfo := make(map[string]ws.ClientAuth)
	for _, key := range keys {
		userInfo, _ := env.Cache.HashGetAll(key)
		uid := userInfo[constant.JwtKeyUserId]
		cauth := ws.ClientAuth{
			UserId:     uid,
			DeptIdList: strings.Split(userInfo[constant.JwtKeyUserDeptIds], ","),
		}
		if uid == "1" {
			cauth.AgencyId = "1"
		} else {
			cauth.AgencyId = userInfo[constant.JwtKeyAgencyId]
		}
		uidMapInfo[uid] = cauth
	}
	ws.AuthInfoRefresh(uidMapInfo)
}
